#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QNetworkDatagram>
#include <QUdpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建对象
    socket = new QUdpSocket(this);
    // 设置窗口相关树形
    this->setWindowTitle("服务器端");

    // 连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);
    // bind 绑定
    bool ret = socket->bind(QHostAddress::Any, 9090);
    if(!ret)
    {
        // 绑定失败
        QMessageBox::critical(this, "服务器绑定失败: ", socket->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

// 服务器核心逻辑
void Widget::processRequest()
{
    // 1. 读取请求+解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram(); // 接收数据报
    QString request = requestDatagram.data(); // 获取数据转到字符串
    // 2. 根据请求 进行响应
    const QString& response = process(request);
    // 3. 将响应写回客户端
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    // 把交互信息显示到界面
    QString log = '[' + requestDatagram.senderAddress().toString() + ':' + QString::number(requestDatagram.senderPort())
            + "] request: " + request + ", response: " + response;
    ui->listWidget->addItem(log);
}

// 进行相应的相关操作
QString Widget::process(const QString &requests)
{
    // 这里只进行回显，直接返回即可
    return requests;
}

